package com.briup.cms.config;

import com.briup.cms.web.interceptor.JwtInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Description
 * @Author lining
 * @Date 2021/7/16 17:21
 * @Version 1.0.0
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override// 添加拦截器方法
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new JwtInterceptor()).addPathPatterns("/auth/**");
    }
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")// 映射所有路径
                .allowedOriginPatterns("*")// 运行所有客户端访问
////不允许携带cookie
                .allowCredentials(false)
//支持的方法
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
//运行所有请求头字段
                .allowedHeaders("*")
//允许客户端缓存“预检请求”中获取的信息，3600秒
                .maxAge(3600);
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new Converter<String, Date>() {
            @Override//提供将时间字符串转换为Date对象的逻辑
            public Date convert(String dateStr) {
                String formatDate = dateStr;
                System.out.println("time:"+dateStr);
                //1.指定字符串转换格式
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                //2.如果字符串格式为 2021-12-20
                if(!dateStr.contains(":")){
                    formatDate = dateStr+" 00:00:00";
                } try {
                    Date date = format.parse(formatDate);
                    return date;
                } catch (ParseException e) {
                    throw new RuntimeException("时间数据格式异常");
                }
            }
        });
    }
}